import { Component, ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import {
  DialogService,
  DValidateRules,
  FormLayout,
  TableWidthConfig,
} from '@devui';
import { LRP } from 'src/app/@core/data/lrp';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { SelectJobOrderProcessComponent } from 'src/app/pages/purchase/purchaseOut/select-job-order-process/select-job-order-process.component';
import { SelectOrderComponent } from 'src/app/pages/sales-master/sales-invoice/select-order/select-order.component';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-add-lrp',
  templateUrl: './add-lrp.component.html',
  styleUrls: ['./add-lrp.component.scss'],
})
export class AddLrpComponent {
  msgs: Array<Object> = [];
  UrlHead: any = environment.modifiedApiUrl;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px',
    },
    {
      field: '物料编码',
      width: '150px',
    },
    {
      field: '图片',
      width: '150px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '物料规格',
      width: '150px',
    },
    {
      field: '物料描述',
      width: '150px',
    },
    {
      field: '物料单位',
      width: '150px',
    },
    {
      field: '数量',
      width: '150px',
    },
    {
      field: '来源单号',
      width: '200px',
    },
    {
      field: '备注',
      width: '150px',
    },
  ]; //表格宽度配置
  lrp: LRP = {
    id: 0,
    lrpNum: '',
    lrpType: '销售订单',
    status: '',
    creator: '',
    createTime: '',
    approvalStatus: '',
    note: '',
    lrpItems: [
      {
        id: 0,
        partNum: '',
        partId: 0,
        image: '',
        partUOM: '',
        partName: '',
        description: '',
        partType: '',
        note: '',
        quantity: 0,
        sourceOrderNum: '',
        sourceOrderType: '',
        sourceOrderPartId: 0,
      },
    ],
  };
  lrpRules: { [key: string]: DValidateRules } = {
    lrpNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*LRP单号不能为空' },
        { minlength: 2, message: '*LRP单号长度至少为2' },
        { maxlength: 40, message: '*LRP单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*LRP单号不能包含空格' },
      ],
    },
    lrpType: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*单据类型不能为空' }],
    },
  };
  options = ['销售订单', '工单'];
  lastType: string = '';
  constructor(
    private DialogService: DialogService,
    private Router: Router,
    private UserService: UserService,
    private EncodeRulesService: EncodeRulesService,
    private ReviewFlowService: ReviewRolesService,
    private cdr: ChangeDetectorRef
  ) {}
  ngOnInit(): void {
    this.EncodeRulesService.GenerateWarehouseCodeRule(
      'LRP单号',
      'LRP单号'
    ).subscribe((data: any) => {
      this.lrp.lrpNum = data;
    });
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.lrp.creator = JSON.parse(userinfoString).username;
    }
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  addRow() {
    this.lrp.lrpItems.push({
      id: 0,
      partNum: '',
      partId: 0,
      image: '',
      partUOM: '',
      partName: '',
      description: '',
      partType: '',
      note: '',
      quantity: 0,
      sourceOrderNum: '',
      sourceOrderType: '',
      sourceOrderPartId: 0,
    });
  } //添加行
  deleteRow(index: number) {
    this.lrp.lrpItems.splice(index, 1);
    if (this.lrp.lrpItems.length == 0) {
      this.addRow();
    }
  }
  submit($event: any) {
    if ($event.valid) {
    } else {
      this.showToast('warn', '错误', '请检查表单是否填写正确');
    }
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  cancel() {
    this.Router.navigateByUrl('/pages/product/lrp');
  }
  selectOrder() {
    if (this.lrp.lrpType == '销售订单') {
      this.selectSaleOrder();
    } else {
      this.selectWorkOrder();
    }
  }
  selectSaleOrder() {
    const saleOrderPartId = this.lrp.lrpItems.map(
      (item: any) => item.sourceOrderPartId
    );
    const results = this.DialogService.open({
      id: 'Add',
      width: '1250px',
      maxHeight: '800px',
      backdropCloseable: true,
      data: {
        saleOrderPartId: saleOrderPartId,
      },
      title: '选择销售订单',
      content: SelectOrderComponent,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.lrp.lrpItems = this.lrp.lrpItems.filter(
              (part) => part.partNum !== '' && part.partNum !== null
            );
            const selectedItems = results.modalContentInstance.filterRows.map(
              (item: any) => {
                return {
                  id: 0,
                  partNum: item.partNum,
                  partId: item.partId,
                  image: item.image,
                  partUOM: item.partUOM,
                  partName: item.partName,
                  description: item.description,
                  partType: item.partType,
                  note: item.note,
                  quantity: item.quantity - item.soldQuantity,
                  sourceOrderNum: item.saleOrderNum,
                  sourceOrderType: '销售订单',
                  sourceOrderPartId: item.saleOrderPartId,
                };
              }
            );
            this.lrp.lrpItems = this.lrp.lrpItems.concat(selectedItems);
            results.modalInstance.hide();
          },
        },
        {
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectWorkOrder() {
    const jobOrderProcessId = this.lrp.lrpItems.map(
      (part) => part.sourceOrderPartId
    );
    const results = this.DialogService.open({
      id: 'Add',
      width: '1200px',
      backdropCloseable: true,
      data: {
        jobOrderProcessId: jobOrderProcessId,
        text: '',
        OutsourcingStatus: '',
      },
      title: '选择工单',
      content: SelectJobOrderProcessComponent,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.lrp.lrpItems = this.lrp.lrpItems.filter(
              (part) => part.partNum !== '' && part.partNum !== null
            );
            const selectedItems = results.modalContentInstance.filterData.map(
              (item: any) => {
                return {
                  id: 0,
                  partNum: item.productNum,
                  partId: item.productId,
                  image: item.i.mage,
                  productUOM: item.uom,
                  partName: item.productName,
                  description: item.description,
                  partType: item.partType,
                  note: item.note,
                  quantity: item.productionQuantity - item.qualifiedAmount,
                  sourceOrderNum: item.jobOrderNum,
                  sourceOrderType: '工单',
                  sourceOrderPartId: item.jobOrderProcessId,
                };
              }
            );
            this.lrp.lrpItems = this.lrp.lrpItems.concat(selectedItems);
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  toggleType($event2: any) {
    this.lastType = this.lrp.lrpType;
    this.lrp.lrpType = $event2;
    console.log(this.lrp.lrpType, this.lastType);
    if ($event2 !== this.lastType) {
      const results = this.DialogService.open({
        id: 'dialog-service',
        maxHeight: '400px',
        width: '300px',
        backdropCloseable: false,
        data: '',
        title: '',
        html: true,
        dialogtype: 'warning',
        content:
          '<div style="color:#8a6d3b;font-size: 14px;">确定切换单据类型，这将会使您构建的物料数据重置！</div>',
        onClose: () => {
          this.cdr.detectChanges(); // 手动触发变更检测
        },

        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.lrp.lrpType = $event2;
              this.lrp.lrpItems = [
                {
                  id: 0,
                  partNum: '',
                  partId: 0,
                  image: '',
                  partUOM: '',
                  partName: '',
                  description: '',
                  partType: '',
                  note: '',
                  quantity: 0,
                  sourceOrderNum: '',
                  sourceOrderType: '',
                  sourceOrderPartId: 0,
                },
              ];

              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
              this.lrp.lrpType = this.lastType;
              this.cdr.detectChanges(); // 手动触发变更检测
              console.log(this.lrp.lrpType);
            },
          },
        ],
      });
    }
  }
}
